package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    //定义超时时间  token一小时有效
    private static long tokenExpiration = 60 * 60 * 1000L;

    //自定义密钥 可以随意修改
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    //生成token密钥
    public static String createToken(Long userId) {
        String token = Jwts.builder().
                setSubject("USER_INFO").   //设置主体
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)). //设定超时时间
                claim("userId", userId).    //自定义的数据 userId
                signWith(tokenSignKey).           //密钥
                compressWith(CompressionCodecs.GZIP). //采用压缩的方式
                compact();                 //生成token
        return token;
    }

    //获取userId
    public static Long parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    setSigningKey(tokenSignKey).
                    build().parseClaimsJws(token);
            return claimsJws.getBody().get("userId", Long.class);
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
